package com.baseweb.webadmin.controller.api;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.BaseState;
import com.baseweb.webadmin.core.constants.CoinType;
import com.baseweb.webadmin.core.constants.Constants;
import com.baseweb.webadmin.core.constants.UserType;
import com.baseweb.webadmin.core.model.bvo.UserForm;
import com.baseweb.webadmin.core.model.pojo.ByUserFeedback;
import com.baseweb.webadmin.core.model.pojo.ByUserInvite;
import com.baseweb.webadmin.core.model.pojo.User;
import com.baseweb.webadmin.core.model.pojo.UserRoleKey;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.service.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping(value = "/api/user/")
public class ApiUserController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiUserController.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private ContentService contentService;

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> login(@RequestParam(value = "mobile", defaultValue = "") String mobile,
                        @RequestParam(value = "password", defaultValue = "") String password) {

        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(password)){
            return fail("数据不能为空!");
        }

        User user = userService.selectByName(mobile);
        if (user != null && password.trim().equals(user.getPassword())){
            if (user.getStatus().intValue() == BaseState.DELETE.getCode()){
                return fail("用户被锁定,请联系客服!");
            }
            if ((user.getUserType().intValue() == UserType.NORMAL_BIZ.getCode())
                    || (user.getUserType().intValue() == UserType.TEAM_BIZ.getCode())
                    || (user.getUserType().intValue() == UserType.NORMAL_USER.getCode())){

                return success(user);
            }else{
                return fail("只有顾客和商家才能登录!");
            }

        }else {
            return fail("用户不存在或密码错误!");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Map<String, Object> register(@RequestParam(value = "mobile", defaultValue = "") String mobile,
                                        @RequestParam(value = "password", defaultValue = "") String password,
                                        @RequestParam(value = "vcode", defaultValue = "") String vcode,
                                        @RequestParam(value = "invite_by", defaultValue = "") String invite_by,
                                        @RequestParam(value = "user_type", defaultValue = "2") String user_type) {

        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(password) || StringUtils.isBlank(vcode)){
            return fail("数据不能为空!");
        }

        User user = userService.selectByName(mobile);
        if (user != null){
            return fail("用户已存在, 手机号已被注册!");
        }else {
            /**
             * 手机号码和发送的手机验证码一致性验证
             */
            String result = CheckCodeUtil.verify(mobile, vcode);

            if ("1".equalsIgnoreCase(result)) {
                User newUser = new User();
                newUser.setUserType(UserType.NORMAL_USER.getCode());
                newUser.setMobile(mobile);
                newUser.setPassword(password.trim());
                newUser.setUsername(mobile);
                newUser.setUserType(Integer.valueOf(user_type));
                newUser.setToken(MD5Util.Md5(newUser.getPassword() + "boyi" + DateUtil.dateToString(new DateTime()) + RandCharUtil.getRandStr(8)));
                newUser.setCnName("user-" + RandCharUtil.getRandStr(8));
                newUser.setStatus(BaseState.NORMAL.getCode());
                newUser.setCreateTime(new DateTime());
                newUser.setUpdateTime(new DateTime());
                newUser.setOrderCount(0);
                newUser.setBizDealCount(0);
                newUser.setCoins(50);
                user.setIsHot(0);
                newUser.setMoney(new BigDecimal("0.00"));
                newUser.setLevelCoins(0);

                userService.insertUser(newUser);

                writeCoinsLog(user, CoinType.REGISTER.getCode(),50);

                User currentUser = userService.selectByName(mobile);
                if (currentUser != null) {
                    UserRoleKey userRoleKey = new UserRoleKey();
                    userRoleKey.setRoleId(2);
                    userRoleKey.setUserId(currentUser.getId());
                    roleService.insertUserRoleKey(userRoleKey);

                    if (StringUtils.isNotBlank(invite_by)){
                        User inviteByUser = userService.selectByName(invite_by);
                        if (inviteByUser != null){
                            ByUserInvite byUserInvite = new ByUserInvite();
                            byUserInvite.setUserId(currentUser.getId());
                            byUserInvite.setInviteBy(inviteByUser.getId());
                            byUserInvite.setStatus(BaseState.DELETE.getCode());
                            byUserInvite.setCreateTime(new DateTime());
                            byUserInvite.setUpdateTime(new DateTime());

                            userService.insertInvite(byUserInvite);
                        }
                    }
                }

                return success(newUser);
            }else{
                return  fail("验证码错误!");
            }
        }
    }

    @ResponseBody
    @RequestMapping(value = "updateAvatar", method = RequestMethod.POST)
    public Map<String, Object> updateAvatar(@RequestParam(value = "token", defaultValue = "") String token,
                             @RequestParam(value = "avatar", defaultValue = "") String avatar) {

        if (!validatedRequest(token) || StringUtils.isBlank(avatar)){
            return illegalRequest();
        }

        User user = currentUser(token);
        user.setAvatar(avatar);
        userService.updateUser(user);
        return success("");
    }

    @ResponseBody
    @RequestMapping(value = "updatePwd", method = RequestMethod.POST)
    public Map<String, Object> updatePwd(@RequestParam(value = "token", defaultValue = "") String token,
                                            @RequestParam(value = "old_password", defaultValue = "") String old_password,
                                            @RequestParam(value = "new_password", defaultValue = "") String new_password) {

        if (!validatedRequest(token) || StringUtils.isBlank(old_password) || StringUtils.isBlank(new_password)){
            return illegalRequest();
        }

        User user = currentUser(token);
        if(old_password.equals(user.getPassword())){
            user.setPassword(new_password);
            userService.updateUser(user);
        }else{
            return fail("旧密码不正确!");
        }
        return success("修改成功!");

    }

    @ResponseBody
    @RequestMapping(value = "forgetPwd", method = RequestMethod.POST)
    public Map<String, Object> sendValidMsg(@RequestParam(value = "mobile", defaultValue = "") String mobile,
                                            @RequestParam(value = "vcode", defaultValue = "") String vcode,
                                            @RequestParam(value = "password", defaultValue = "") String password) {

        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(vcode) || StringUtils.isBlank(password)){
            return illegalRequest();
        }

        User user = userService.selectByName(mobile);
        if (user == null){
            return fail("用户不存在!");
        }else {
            /**
             * 手机号码和发送的手机验证码一致性验证
             */
            String result = CheckCodeUtil.verify(mobile, vcode);

            if ("1".equalsIgnoreCase(result)) {
                user.setPassword(password.trim());
                user.setUpdateTime(new DateTime());
                userService.updateUser(user);
            }else{
                return fail("验证码不正确!");
            }
        }

        return success("修改成功!");

    }

    @ResponseBody
    @RequestMapping(value = "submitFeedback", method = RequestMethod.POST)
    public Map<String, Object> submitFeedback(@RequestParam(value = "token", defaultValue = "") String token,
                                            @RequestParam(value = "content", defaultValue = "") String content) {

        if (!validatedRequest(token) || StringUtils.isBlank(content)){
            return illegalRequest();
        }

        User user = currentUser(token);

        ByUserFeedback byUserFeedback = new ByUserFeedback();
        byUserFeedback.setDescn(content);
        byUserFeedback.setStatus(BaseState.DELETE.getCode());
        byUserFeedback.setCreateTime(new DateTime());
        byUserFeedback.setUpdateTime(new DateTime());

        contentService.insertFeedback(byUserFeedback);

        return success("修改成功!");

    }



}
